/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package processor;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author DYNG09
 */
public class TemplateStatement {

    private ArrayList<String> lstNameTemplate;
    private ArrayList<String> lstTemplate;
    private Document doc;

    /**
     * Constructor
     */
    public TemplateStatement() {
        doc = parseXML("src/data/template.xml");
        lstNameTemplate = new ArrayList();
        lstTemplate = new ArrayList();
        loadNameTemplate(doc, lstNameTemplate, lstTemplate);
    }

    /**
     * load list template in document
     *
     * @param doc
     * @return
     */
    private void loadNameTemplate(Document doc,
            ArrayList<String> lstName, ArrayList<String> lstTem) {
        NodeList list = doc.getElementsByTagName("item");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);

            Element e = (Element) node;
            lstName.add(e.getAttribute("name"));
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                NodeList nl = node.getChildNodes();
                Node node2 = nl.item(0);
                lstTem.add(node2.getNodeValue());
            }
        }
    }

    /**
     * load xml document
     *
     * @param path link to xml file
     * @return a document xml parsed
     */
    private Document parseXML(String path) {
        Document doc = null;
        try {
            File fileXML = new File(path);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(fileXML);
            doc.getDocumentElement().normalize();
        } catch (SAXException ex) {
            Logger.getLogger(TemplateStatement.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TemplateStatement.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(TemplateStatement.class.getName()).log(Level.SEVERE, null, ex);
        }

        return doc;
    }

    /**
     * @return the lstNameTemplate
     */
    public ArrayList<String> getLstNameTemplate() {
        return lstNameTemplate;
    }

    /**
     * @return the lstTemplate
     */
    public ArrayList<String> getLstTemplate() {
        return lstTemplate;
    }
}
